package com.ishopping.service.manage.service.impl;

import com.ishopping.common.core.base.service.AbstractBaseService;
import com.ishopping.common.core.utils.security.DigestUtils;
import com.ishopping.common.core.utils.security.EncodeUtils;
import com.ishopping.service.manage.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ishopping.api.manage.entity.User;
import com.ishopping.api.manage.service.IUserService;
import com.ishopping.common.core.base.exception.ServiceException;
import org.springframework.transaction.annotation.Transactional;
@Service("userService")
public class UserServiceImpl extends AbstractBaseService<User> implements IUserService {

	/**加密方法*/
	public static final String HASH_ALGORITHM = "SHA-1";

	public static final int HASH_INTERATIONS = 1024;

	private static final int SALT_SIZE = 8;	//盐长度
	
	@Autowired
	private UserMapper userMapper;


	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	@Override
	@Transactional
	public int doSave(User user) {
		//用户校验
		validate(user);
		//加密用户
		entryptPassword(user);
		//更新数据库
		int result = save(user);
		return result;
	}

	/**
	 * 用户校验
	 * @param user
	 */
	@Override
	public void validate(User user){
		String username = user.getUsername();
		if(StringUtils.isBlank(username)){
			throw new ServiceException("请输入用户名！");
		}
		User u = this.queryOne(user);
		if (u != null) {
			throw new ServiceException("用户已存在！");
		}

		if(user.getUsername() == null || user.getPassword() == null) {
			throw new ServiceException("用户名或者密码不能为空！");
		}
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 * @param user
	 */
	private void entryptPassword(User user) {
		byte[] salt = DigestUtils.generateSalt(SALT_SIZE);
		user.setSalt(EncodeUtils.encodeHex(salt));

		byte[] hashPassword = DigestUtils.sha1(user.getPassword().getBytes(),salt, HASH_INTERATIONS);
		user.setPassword(EncodeUtils.encodeHex(hashPassword));
	}
}
